package pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


public class GeneratePDF {
    /**
     * HTML 转 PDF
     * @param content html内容
     * @param outPath           输出pdf路径
     * @return 是否创建成功
     */
    public static boolean html2Pdf(String content, String outPath) {
        try {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPath));
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new ByteArrayInputStream(content.getBytes()), null, StandardCharsets.UTF_8);
            document.close();
        } catch (Exception e) {
            System.out.println("生成模板内容失败"+e.fillInStackTrace());
            return false;
        }
        return true;
    }
    /**
     * HTML 转 PDF
     * @param content html内容
     * @return PDF字节数组
     */
    public static ByteArrayOutputStream html2Pdf(String content) {
        ByteArrayOutputStream outputStream = null;
        try {
            Document document = new Document();
            outputStream = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new ByteArrayInputStream(content.getBytes()), null, StandardCharsets.UTF_8);
            document.close();
        } catch (Exception e) {
            System.out.println("------生成pdf失败-------");
        }
        assert outputStream != null;
        return outputStream;
    }

    public static String PATH = "D:\\\\A.pdf";
    public static String PNG_PATH = "C:\\Users\\PC-a\\Desktop\\nft.png";
    public static String OUT_PATH = "C:\\Users\\PC-a\\Desktop\\new.pdf";

    public static void main(String[] args) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
        paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
        /*String outPath = "D:\\A.pdf";*/
        String templateDirectory = "src/main/resources/templates";
        String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
        ByteArrayOutputStream outputStream = GeneratePDF.html2Pdf(templateContent);

        byte[] bytes = outputStream.toByteArray();
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        InputStream pdfInputStream = new ByteArrayInputStream(buffer.array());

//        2、得到PDF文档对象
        PDDocument pdDocument = PDDocument.load(pdfInputStream);
//        3、由Document得到Page对象
        PDPage page = pdDocument.getPage(0);
//        4、通过图片路径和PDF文档对象得到图片image对象
        PDImageXObject image = PDImageXObject.createFromFile(PNG_PATH, pdDocument);
//        5、创建pageStream对象
        PDPageContentStream pageStream = new PDPageContentStream(pdDocument, page, PDPageContentStream.AppendMode.APPEND, false, false);

//   6、pageStream对象绘制图片位置及大小，已PDF文件右下角为原点（x,y）是图片左下角左边，width、height是图片的长和宽
        pageStream.drawImage(image, 55, 625, 100, 100);

        pageStream.close();

//    7、保存PDF到指定路劲
        pdDocument.save(OUT_PATH);

//      8、关闭流
        pdDocument.close();
        outputStream.close();
        pdfInputStream.close();



    }

}
